package com.fs.uc.security;

import com.fs.uc.base.domain.Org;
import com.fs.uc.base.domain.OrgType;
import com.fs.uc.base.domain.Person;
import com.fs.uc.core.SubjectType;
import io.smallrye.jwt.algorithm.SignatureAlgorithm;
import io.smallrye.jwt.auth.principal.JWTParser;
import io.smallrye.jwt.auth.principal.ParseException;
import io.smallrye.jwt.build.Jwt;
import io.smallrye.jwt.build.JwtClaimsBuilder;
import org.eclipse.microprofile.jwt.JsonWebToken;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Date;

/**
 * @author 崔超
 * 2021/12/3
 */
@ApplicationScoped
public class JwtUtil {
    @Inject
    JWTParser parser;

    static final long EXPIRE_TIME = 60 * 60 * 1000 * 12;
    static final String SUBJECT_TYPE = "type";
    static final String SECRET = "fj6K!p2UO^%fJ18&^fLb3K5S5kjb*1ho";

    public String buildToken(Org org) {
        return buildToken(org.id, SubjectType.Org);
    }

    public String buildToken(Person person) {
        return buildToken(person.id, SubjectType.Person);
    }

    private String buildToken(Long subject, SubjectType type) {
        JwtClaimsBuilder builder = Jwt.claims();
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        builder.subject(subject.toString())
                .expiresAt(date.toInstant())
                .claim(SUBJECT_TYPE, type.name());
        return builder.jws().algorithm(SignatureAlgorithm.HS256).signWithSecret(SECRET);
    }

    public JwtUserInfo getUserInfo(String token) throws ParseException {
        JsonWebToken res = parser.verify(token, SECRET);
        String subject = res.getSubject();
        SubjectType subjectType = SubjectType.valueOf(res.getClaim(SUBJECT_TYPE));
        return new JwtUserInfo(Long.parseLong(subject), subjectType);
    }

}
